package com.easy.work.function.main;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.base.syslib.Logs;
import com.base.syslib.util.AndroidUtils;
import com.base.syslib.util.MessageTools;
import com.base.syslib.util.TextUtil;
import com.base.syslib.view.ObservableScrollView;
import com.base.syslib.view.viewpager.CarouseFigureBean;
import com.base.syslib.view.viewpager.CycleViewPager;
import com.easy.work.MainActivity;
import com.easy.work.R;
import com.easy.work.app.AppSession;
import com.easy.work.app.BaseActivity;
import com.easy.work.bean.CompanyBriefBean;
import com.easy.work.bean.WorkBaseInfo;
import com.easy.work.function.WebViewAct;
import com.easy.work.function.main.adapter.CompanyPicturePageAdapter;
import com.easy.work.function.main.fragment.InputRecommendFragment;
import com.easy.work.function.resume.MyResumeAct;
import com.easy.work.http.BaseResponse;
import com.easy.work.http.HttpClient;
import com.easy.work.http.request.CancleCollectRequest;
import com.easy.work.http.request.WorkApplyRequest;
import com.easy.work.http.request.WorkBaseDetailInfoRequest;
import com.easy.work.http.request.WorkCollectRequest;
import com.easy.work.http.response.WorkCollectResponse;
import com.easy.work.type.DeliveryType;
import com.easy.work.utils.OpenMap;
import com.easy.work.utils.StringUtil;
import com.easy.work.utils.ViewFactory;
import com.easy.work.view.dialog.SignUpDialog;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/12/16.
 * 招聘信息详情
 */
public class WorkBaseDetailAct extends BaseActivity implements ObservableScrollView.ScrollViewListener {

    @BindView(R.id.scrollView)
    ObservableScrollView scrollView;
    @BindView(R.id.titleLayout)
    RelativeLayout titleLayout;
    //    @BindView(R.id.viewPager)
//    ViewPager viewPager;
//    @BindView(R.id.tv_picture_number)
//    TextView tvPictureNumber;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_work_salary)
    TextView tvWorkSalary;
    @BindView(R.id.img_shoucang)
    ImageView imgShoucang;
    @BindView(R.id.tv_shoucang)
    TextView tvShoucang;
    @BindView(R.id.ll_dadianhua)
    LinearLayout llDadianhua;
    @BindView(R.id.imageView_phone)
    ImageView imageViewPhone;

    @BindView(R.id.ll_shoucang)
    LinearLayout llShoucang;
    @BindView(R.id.tv_work_conditions)
    TextView tvWorkConditions;
    @BindView(R.id.tv_work_content)
    TextView tvWorkContent;
    @BindView(R.id.tv_work_time)
    TextView tvWorkTime;
    @BindView(R.id.rl_back)
    RelativeLayout rlBack;
    @BindView(R.id.title_txt)
    TextView titleTxt;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.tv_work_wages)
    TextView tvWorkWages;
    @BindView(R.id.tv_work_welfare)
    TextView tvWorkWelfare;
    @BindView(R.id.img_company_small)
    ImageView imgCompanySmall;
    @BindView(R.id.tv_company_post)
    TextView tvCompanyPost;
    @BindView(R.id.tv_company_type)
    TextView tvCompanyType;
    @BindView(R.id.tv_woyaotuijian)
    TextView tvWoyaotuijian;
    @BindView(R.id.tv_woyaobaoming)
    TextView tvWoyaobaoming;
    private String workId = "";
    /**
     * title变色高度
     */
    private int length;

    private WorkBaseInfo bean;
    private CycleViewPager cycleViewPager;

    public static void start(Context context, String workId) {
        Intent intent = new Intent(context, WorkBaseDetailAct.class);
        intent.putExtra("workId", workId);
        context.startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.hasExtra("workId")) {
            workId = intent.getStringExtra("workId");
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_work_base_detail);
        ButterKnife.bind(this);
        cycleViewPager = (CycleViewPager) getFragmentManager()
                .findFragmentById(R.id.work_detail_viewPager);
        titleTxt.setText("详情");
        titleTxt.setAlpha(0);
        if (getIntent().hasExtra("workId")) {
            workId = getIntent().getStringExtra("workId");
        }
        getData();
        initScroView();
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        getData();
    }

    void getData() {
        final WorkBaseDetailInfoRequest request = new WorkBaseDetailInfoRequest();
        request.userId = AppSession.getInstance().getUserId();
        request.workId = workId;
        showDialog();
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                closeDialog();
                Logs.e("mainfragment", "response");
                bean = (WorkBaseInfo) response;
                if (bean == null) {
                    MessageTools.showToast(WorkBaseDetailAct.this, "获取详情失败");
                    return;
                }
                setMessage(bean);

            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                Logs.d("MainFragment", "WorkBaseListInfoRequest    code" + code + "      msg=" + msg);
                closeDialog();
            }
        });
    }

    /**
     * 加载轮播图
     *
     * @param infos
     */
    @SuppressLint("NewApi")
    private void initialize(List<CompanyBriefBean.PictureListEntity> infos) {
        if (infos == null || infos.size() < 1) {
            return;
        }

        List<CarouseFigureBean> list = new ArrayList<>();
        for (CompanyBriefBean.PictureListEntity entity : infos) {
            CarouseFigureBean carouseFigureBean = new CarouseFigureBean();
            carouseFigureBean.imgAddress = entity.companyImage;
            list.add(carouseFigureBean);

        }
        List<ImageView> views = new ArrayList<ImageView>();
        // 将最后一个ImageView添加进来
        views.add(ViewFactory.getImageView(this, infos.get(infos.size() - 1).companyImage));
        for (int i = 0; i < infos.size(); i++) {
            views.add(ViewFactory.getImageView(this, infos.get(i).companyImage));
        }
        // 将第一个ImageView添加进来
        views.add(ViewFactory.getImageView(this, infos.get(0).companyImage));

        // 设置循环，在调用setData方法前调用
        cycleViewPager.setCycle(true);

        // 在加载数据前设置是否循环
        cycleViewPager.setData(views, list, mAdCycleViewListener);
        //设置轮播
        cycleViewPager.setWheel(true);

        // 设置轮播时间，默认5000ms
        cycleViewPager.setTime(2000);
        //设置圆点指示图标组居中显示，默认靠右
        cycleViewPager.setIndicatorCenter();
    }

    private CycleViewPager.ImageCycleViewListener mAdCycleViewListener = new CycleViewPager.ImageCycleViewListener() {

        @Override
        public void onImageClick(CarouseFigureBean info, int position, View imageView) {
        }

    };

//    private void addTitleViewPager(WorkBaseInfo bean) {
//        // 公司图片显示
//        List<CompanyBriefBean.PictureListEntity> picList = bean.imageList;
//        if (picList != null && !picList.isEmpty()) {
//            tvPictureNumber.setText(String.valueOf(picList.size()));
//            Logs.e(tag, "pic_size:" + picList.size());
//            List<View> list = new ArrayList<>();
//            for (CompanyBriefBean.PictureListEntity entity : picList) {
//                View v = getLayoutInflater().inflate(R.layout.item_company_pic, null);
//                ImageView iv = (ImageView) v.findViewById(R.id.iv_pic);
//                Picasso.with(this).load(entity.companyImage).into(iv);
//                list.add(v);
//            }
//            viewPager.setAdapter(new CompanyPicturePageAdapter(list));
//        }
//    }

    /**
     * 设置数据
     */
    private void setMessage(WorkBaseInfo bean) {

        if (!StringUtil.isEmpty(bean.phoneIsShow) && bean.phoneIsShow.equals("1")) {
            Picasso.with(this).load(R.mipmap.dianhua_has).into(imageViewPhone);
        } else {
            Picasso.with(this).load(R.mipmap.dianhua).into(imageViewPhone);
        }
        if (bean.imageList != null) {
            initialize(bean.imageList);
        }

//        addTitleViewPager(bean);
        Picasso.with(this).load(bean.workImage).into(imgCompanySmall);
        tvTitle.setText(bean.title);
        tvWorkSalary.setText(bean.salaryFrom + "—" + bean.salaryTo + "元/月");
        if (bean.isCollect == 0) {
            imgShoucang.setBackground(getResources().getDrawable(R.mipmap.weishoucang));
            tvShoucang.setText("收藏");
        } else if (bean.isCollect == 1) {
            imgShoucang.setBackground(getResources().getDrawable(R.mipmap.yishoucang));
            tvShoucang.setText("已收藏");
        }
        tvWorkContent.setText(bean.workContent);
        tvWorkTime.setText(bean.workTime);
//        StringBuffer stringBuffer = new StringBuffer("");
//        List<String> conditionList = bean.conditionList;
//        if (conditionList != null && conditionList.size() > 0) {
//            for (int i = 0; i < conditionList.size(); i++) {
//                stringBuffer.append(conditionList.get(i))
//                        .append("\n");
//            }
//            stringBuffer.deleteCharAt(stringBuffer.length() - 1);
//        } else {
//            stringBuffer.append("不限");
//        }
        tvWorkConditions.setText(bean.conditions);
        tvAddress.setText(bean.provinceText + bean.cityText + bean.areaText + bean.companyAddress + "");
        tvWorkWages.setText(bean.wages);
        tvWorkWelfare.setText(bean.welfare);
        tvCompanyPost.setText(bean.companyName);
        tvCompanyType.setText("企业规模: " + bean.companySize + "人以上");
        Picasso.with(this).load(bean.companyImage).into(imgCompanySmall);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {

                case 1:
                    llShoucang.setClickable(true);
                    break;
            }
        }
    };

    @OnClick({R.id.ll_shoucang, R.id.ll_dadianhua, R.id.rl_back, R.id.tv_woyaotuijian, R.id.tv_woyaobaoming, R.id.ll_address})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_shoucang:
                if (bean == null) {
                    return;
                }
                llShoucang.setClickable(false);
                mHandler.sendEmptyMessageDelayed(1, 2 * 1000);
                if (TextUtil.isNull(bean.collectId) || bean.collectId.equals("0")) {
                    workCollect();
                } else {
                    cancleCollect();
                }

                break;
            case R.id.ll_dadianhua:
                if (StringUtil.isEmpty(bean.phone)) {
                    return;
                }

                if (!bean.phoneIsShow.equals("1")) {
                    return;
                }
                MessageTools.showDialog(oThis, "是否拨打电话:  " + bean.phone, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        AndroidUtils.toCallView(oThis, bean.phone);
                    }
                });

                break;
            case R.id.rl_back:
                MainActivity.startActivity(oThis);
                break;
            case R.id.tv_woyaotuijian:
                //我要推荐
                if (bean == null || TextUtil.isNull(bean.workId)) {
                    return;
                }
                InputRecommendFragment.start(this, bean.workId);
                break;
            case R.id.tv_woyaobaoming:
                if (bean == null || TextUtil.isNull(bean.workId)) {
                    return;
                }
                if (bean.isApplyed == 1) {
                    MessageTools.showDialogOk(oThis, "您已经投递该工作，请勿重复提交");
                    return;
                }
                if (AppSession.getInstance().isResumePerfect()) {
                    workApply();
                } else {
                    setWoyaobaoming();
                }

                break;
            case R.id.ll_address:
                //导航
                if (bean == null || TextUtil.isNull(bean.workId)) {
                    return;
                }
                OpenMap openMap = new OpenMap();
                openMap.openBaiDuMap(oThis, bean.companyName, bean.latitude, bean.longitude);

                break;
        }
    }

    /**
     * 收藏
     */
    private void workCollect() {
        WorkCollectRequest request = new WorkCollectRequest();
        request.userId = AppSession.getInstance().getUserId();
        request.workId = bean.workId;
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                MessageTools.showToast(oThis, "收藏成功");
                WorkCollectResponse workCollectRequest = (WorkCollectResponse) response;
                bean.isCollect = 1;
                bean.collectId = workCollectRequest.collectId;
                imgShoucang.setBackground(getResources().getDrawable(R.mipmap.yishoucang));
                tvShoucang.setText("已收藏");
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(oThis, msg);

            }
        });
    }

    /**
     * 取消收藏
     */
    private void cancleCollect() {
        CancleCollectRequest request = new CancleCollectRequest();
        request.collectId = bean.collectId;
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                MessageTools.showToast(oThis, "取消收藏成功");
                imgShoucang.setBackground(getResources().getDrawable(R.mipmap.weishoucang));
                bean.collectId = "0";
                tvShoucang.setText("收藏");
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(oThis, msg);

            }
        });
    }

    /**
     * 我要报名
     */
    private void setWoyaobaoming() {
        SignUpDialog.Builder builder = new SignUpDialog.Builder(this);

        builder.create(new SignUpDialog.ImproveResumeListener() {
            @Override
            public void improveResumeListener(SignUpDialog dialog) {
                //完善简历
                MyResumeAct.startActivity(oThis);
            }
        }, new SignUpDialog.ContinueToPostListener() {
            @Override
            public void continueToPostListener(SignUpDialog dialog) {
                //继续投递
                workApply(dialog);
            }
        }).show();
    }

    /**
     * 报名
     *
     * @param dialog
     */
    private void workApply(final SignUpDialog dialog) {
        WorkApplyRequest request = new WorkApplyRequest();
        request.userId = AppSession.getInstance().getUserId();
        request.workId = bean.workId;
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                MessageTools.showToast(oThis, "报名成功");
                dialog.dismiss();
                SignUpSuccessAct.start(oThis, DeliveryType.SignUp);
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(oThis, msg);
                dialog.dismiss();
            }
        });
    }

    /**
     * 报名
     */
    private void workApply() {
        WorkApplyRequest request = new WorkApplyRequest();
        request.userId = AppSession.getInstance().getUserId();
        request.workId = bean.workId;
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                MessageTools.showToast(oThis, "报名成功");
                SignUpSuccessAct.start(oThis, DeliveryType.SignUp);
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(oThis, msg);
            }
        });
    }

    private void initScroView() {
        length = 250;

        scrollView.setScrollViewListener(WorkBaseDetailAct.this);
//        viewPcager.setFocusable(true);
//        viewPager.setFocusableInTouchMode(true);
//        viewPager.requestFocus();
//        ViewTreeObserver vto = viewPager.getViewTreeObserver();
//        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
//            @Override
//            public void onGlobalLayout() {
//                viewPager.getViewTreeObserver().removeGlobalOnLayoutListener(
//                        this);
//                length = viewPager.getHeight();
//
//                scrollView.setScrollViewListener(WorkBaseDetailAct.this);
//            }
//        });
//        scrollView.scrollBy(0, 0);
//        scrollView.scrollTo(0, 0);
    }

    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        if (y <= 0) {
            titleLayout.setBackgroundColor(Color.argb((int) 0, 255, 144, 00));//AGB由相关工具获得，或者美工提供
            titleTxt.setAlpha(0);
        } else if (y > 0 && y <= length) {
            float scale = (float) y / length;
            float alpha = (255 * scale);
            // 只是layout背景透明(仿知乎滑动效果)
            titleLayout.setBackgroundColor(Color.argb((int) alpha, 255, 144, 00));
            titleTxt.setAlpha(alpha / 255);
        } else {
            titleLayout.setBackgroundColor(Color.argb((int) 255, 255, 144, 00));
            titleTxt.setAlpha(1);
        }

    }

    @OnClick({R.id.tv_company_brief, R.id.ll_work_introduction})
    public void companyBrief() {
        if (bean == null) {
            MessageTools.showToast(WorkBaseDetailAct.this, "获取企业失败");
            return;
        }
        CompanyBriefActivity.start(WorkBaseDetailAct.this, bean.companyId);
    }
}
